package com.ailk.tcm.hffw.android.common.network;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;

/**
 * 每次请求把所有的cookie带过去以解决session的问题
 * @author Chris
 *
 */
public class HttpUtil extends FinalHttp{
	private static Object cookies;
	
	public HttpUtil(){
		super();
		DefaultHttpClient httpClient = (DefaultHttpClient) getHttpClient();
		httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
			@Override
			public void process(HttpRequest request, HttpContext httpContext)
					throws HttpException, IOException {
				if(cookies != null){
					httpContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
				}
			}
		});
		
		httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
			
			@Override
			public void process(HttpResponse response, HttpContext context)
					throws HttpException, IOException {
				cookies = context.getAttribute(ClientContext.COOKIE_STORE);
			}
		});
	}
	
	public void post(String url, String body, AjaxCallBack<? extends Object> callBack){
		try {
			post(url, new ByteArrayEntity(body.getBytes("UTF-8")), "application/json;utf-8", callBack);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
}
